import React, { useState } from 'react';
import { Form, Input, Button, Card, Avatar, Typography } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';

const { Title, Text } = Typography;

interface LoginFormProps {
  onLogin: (username: string, password: string) => Promise<void>;
}

const LoginForm = ({ onLogin }: LoginFormProps) => {
  const [loading, setLoading] = useState(false);
  
  const onFinish = async (values: { username: string; password: string }) => {
    setLoading(true);
    try {
      await onLogin(values.username, values.password);
    } catch (error) {
      console.error('Login failed', error);
    } finally {
      setLoading(false);
    }
  };

  return ( 
    <Card>
      <Form
        name="login"
        initialValues={{ username: 'admin', password: '' }}
        onFinish={onFinish}
      >
        <Form.Item
          name="username"
          rules={[{ required: true, message: '请输入用户名!' }]}
        >
          <Input 
            prefix={<UserOutlined />} 
            placeholder="用户名" 
            size="large"
          />
        </Form.Item>

        <Form.Item
          name="password"
          rules={[{ required: true, message: '请输入密码!' }]}
        >
          <Input.Password
            prefix={<LockOutlined />}
            placeholder="密码"
            size="large"
          />
        </Form.Item>

        <Form.Item>
          <Button 
            type="primary" 
            htmlType="submit" 
            loading={loading}
            block
            size="large"
          >
            登录
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
};

interface UserInfoProps {
  username: string;
  onLogout: () => Promise<void>;
}

const UserInfo = ({ username, onLogout }: UserInfoProps) => {
  return ( 
    <Card 
      title="用户信息" 
      className="auth-card"
      actions={[
        <Button key="logout" type="primary" danger onClick={onLogout} block>
          退出登录
        </Button>
      ]}
    >
      <div className="user-info">
        <Avatar 
          size={64} 
          icon={<UserOutlined />} 
          className="user-avatar" 
        />
        <div className="user-text">
          <Title level={4}>{username}</Title>
          <Text type="secondary">已认证用户</Text>
        </div>
      </div>
    </Card>
  );
};

interface AuthModuleProps {
  isAuthenticated: boolean;
  user: { username: string } | null;
  onLogin: (username: string, password: string) => Promise<void>;
  onLogout: () => Promise<void>;
}

const AuthModule = ({ 
  isAuthenticated, 
  user,
  onLogin,
  onLogout 
}: AuthModuleProps) => {
  return (
    <div style={{ marginBottom: 24 }}>
      {isAuthenticated ? (
        <UserInfo username={user?.username || ''} onLogout={onLogout} />
      ) : (
        <LoginForm onLogin={onLogin} />
      )}
    </div>
  );
};

export default AuthModule;